/**
 * Created by wust on 2019-12-25 08:44:03
 * Copyright © 2019 wust. All rights reserved.
 */
package com.sc.common.interceptors.dataprivilege;

import cn.hutool.core.collection.CollectionUtil;
import com.sc.common.context.DefaultBusinessContext;
import com.sc.common.enums.RedisKeyEnum;
import com.sc.common.util.MyStringUtils;
import com.sc.common.util.ReflectHelper;
import com.sc.common.util.cache.SpringRedisTools;
import org.apache.ibatis.executor.statement.BaseStatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
import java.util.Set;

/**
 * @author: wust
 * @date: Created in 2019-12-25 08:44:03
 * @description: 总公司账号数据权限策略
 *
 */
@Service("parentCompanyAccountStrategy")
public class ParentCompanyAccountStrategy implements IStrategy{
    @Autowired
    private SpringRedisTools springRedisTools;


    @Override
    public void bindSql(BaseStatementHandler delegate) {
        DefaultBusinessContext ctx = DefaultBusinessContext.getContext();

        BoundSql boundSql = delegate.getBoundSql();

        String sql = boundSql.getSql();

        StringBuffer privilegeSqlStringBuffer = new StringBuffer("SELECT privilege_tmp.* FROM (" + sql + ") privilege_tmp");

        Map map = springRedisTools.getMap(String.format(RedisKeyEnum.REDIS_KEY_HASH_GROUP_BRANCH_COMPANY_BY_USER_ID.getStringValue(),ctx.getAccountId()));
        if(CollectionUtil.isNotEmpty(map)){
            String companyIds = "";
            Set keys = map.keySet();
            for (Object o : keys) {
                Map company = map.get(o.toString()) == null ? null : (Map)map.get(o.toString());
                if(MyStringUtils.isNotBlank(companyIds)){
                    companyIds += "," + company.get("id");
                }else{
                    companyIds +=  company.get("id");
                }
            }
            privilegeSqlStringBuffer.append(" WHERE company_id IN (" + companyIds + ") OR creater_id = " + ctx.getAccountId());
        }

        ReflectHelper.setValueByFieldName(boundSql, "sql", privilegeSqlStringBuffer.toString());
    }
}
